<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>localStorage</title>
</head>
<body>
<script>
    'use strict';
    (function () {
        var ls = window.localStorage
        function oops() {
            return console.warn('' +
                'your browser is not supported localStorge API')
        }
        function getItem(key) {
            var data = ls.getItem(key)
            //对字符串类型要进行转换,如果是null就用空对象包裹
            data = JSON.parse(data) || {}
            if(data.time === 0){
                return data.value
            }else if(Date.now()>data.time){
                ls.removeItem(key)
                return ''
            }else{
                return typeof data.value !=='undefined' ? data.value : ''
            }

        }
        function setItem(key,value,time) {
            if(typeof key === "undefined"){return}
            var data = {
                time : time ? Date.now()+time :0,
                value : value
            }
            //进行字符串序列化
            data = JSON.stringify(data)

            try{
                ls.setItem(key,data)
            }catch(e){
                //一旦超出容量，将数据全部清空,然后再存储数据
                ls.clear()
                ls.setItem(key,data)
            }

        }
        function removeItem(key) {
            ls.removeItem(key)
        }
        function clear() {
            ls.clear()
        }
        window.cacheStorage = {
            getItem: ls ? getItem : oops,
            setItem: ls ? setItem : oops,
            removeItem: ls ? removeItem : oops,
            clear: ls ? clear : clear,
        }

    })
</script>


</body>
</html>